package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author vvv
 * @date 2023-10-31 15 58
 * discription
 */
public class MyLock implements ILock{
    /**
     * 锁名称
     */
    private String key;
    /**
     * 操作redis
     */
    private StringRedisTemplate stringRedisTemplate;

    /**
     * JVM唯一标识
     */
    public static final String JVM_TOKEN = UUID.randomUUID().toString(true);

    /**
     * 锁的过期时间
     */
    public static final int LOCK_EXPIRE_TIME = 5;

    /**
     * unlock的Lua脚本
     */
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    /**
     * tryLock的Lua脚本
     */
    private static final DefaultRedisScript<Long> TRYLOCK_SCRIPT;

    static {
        TRYLOCK_SCRIPT = new DefaultRedisScript<>();
        TRYLOCK_SCRIPT.setLocation(new ClassPathResource("reentrantLockTryLock.lua"));
        TRYLOCK_SCRIPT.setResultType(Long.class);

        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("reentrantLockUnlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public MyLock(String key, StringRedisTemplate stringRedisTemplate) {
        this.key = key;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock() {
        Long result = stringRedisTemplate.execute(
                TRYLOCK_SCRIPT,
                Collections.singletonList(key),
                JVM_TOKEN + "-" + Thread.currentThread().getId(), String.valueOf(LOCK_EXPIRE_TIME)
        );
        return result == 1;
    }

    @Override
    public void unlock() {
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(key),
                JVM_TOKEN + "-" + Thread.currentThread().getId(), String.valueOf(LOCK_EXPIRE_TIME)
        );
    }
}
